﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using fuzhu;
using XXX.Models.XXXEntities;
using XXX.Models;
using LH.Model.SA;
using LH.Model.APAR;
using LH.U8API.Bus;
using U8COWeb;
using XXX.Common;

namespace XXX.Bo
{
   public  partial class U8API
    {

        public RetModelbool InsertSaleOrder(SaleOrder saleOrder)
        {
            RetModelbool ret = new RetModelbool();
            string constr = CanShu.conStr;
            // 订单的汇总金额，原币金额
            decimal iAmount = 0.00m, iAmount_f = 0.00m;
            string sql = "";
            using (SqlConnection connection = new SqlConnection(constr))
            {
                connection.Open();
                SqlTransaction tran = connection.BeginTransaction();
                try
                {
                    //销售单号检查
                    if (string.IsNullOrEmpty(saleOrder.head.cSOCode))
            {
                throw new Exception("销售单号不能为空");
            }
            else
            {
                sql = string.Format("select count(*) from so_somain where csocode='{0}'", saleOrder.head.cSOCode);
                int icnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, constr));
                if (icnt > 0)
                {
                    throw new Exception("销售单号已存在");
                }
            }
            //客户编码检查
            if (string.IsNullOrEmpty(saleOrder.head.cCusCode))
            {
                throw new Exception("客户编码不能为空");
            }
            else
            {
                sql = string.Format("select count(*) from customer where ccuscode='{0}'", saleOrder.head.cCusCode);
                int icnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, constr));
                if (icnt == 0)
                {
                    throw new Exception("客户编码不存在");
                }
            }
            //币种检查
            if (string.IsNullOrEmpty(saleOrder.head.cExch_name))
            {
                throw new Exception("币种不能为空");
            }
            //业务员，读取部门编码
            if (!string.IsNullOrEmpty(saleOrder.head.cPersonCode))
            {
                sql = string.Format("select cdepcode from person where cpersoncode='{0}'", saleOrder.head.cPersonCode);
                DataTable dtperson = DbHelper2.ExecuteTable(sql, constr);
                if (dtperson.Rows.Count > 0)
                {
                    saleOrder.head.cDepCode = DbHelper.GetDbString(dtperson.Rows[0]["cdepcode"]);
                }
                else
                {
                    throw new Exception("业务员编码不正确");
                }
            }

            if (string.IsNullOrEmpty(saleOrder.head.dDate))
            {
                throw new Exception("订单日期不能为空");
            }
            if (string.IsNullOrEmpty(saleOrder.head.cMaker))
            {
                throw new Exception("制单人不能为空");
            }

            if (string.IsNullOrEmpty(saleOrder.head.iExchRate) || saleOrder.head.iExchRate == "0")
            {
                throw new Exception("汇率不能为0");
            }
            if (saleOrder.bodies == null || saleOrder.bodies.Count == 0)
            {
                throw new Exception("表体不能为空");
            }
            for (int i = 0; i < saleOrder.bodies.Count; i++)
            {
                if (string.IsNullOrEmpty(saleOrder.bodies[i].cInvCode))
                {
                    throw new Exception(string.Format("第{0}行存货编码不能为空", (i + 1)));
                }
                else
                {
                    sql = string.Format("select count(*) from inventory where cinvcode='{0}'", saleOrder.bodies[i].cInvCode);
                    int icnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, constr));
                    if (icnt == 0)
                    {
                        throw new Exception(string.Format("第{0}行存货编码不存在", (i + 1)));
                    }
                }

                if (saleOrder.bodies[i].iQuantity == 0)
                {
                    throw new Exception(string.Format("第{0}行数量不能为0", (i + 1)));
                }

                if (string.IsNullOrEmpty(DbHelper.GetDbString(saleOrder.bodies[i].dPreDate)))
                {
                    throw new Exception(string.Format("第{0}行预计发货日期不能为空", (i + 1)));
                }

                if (string.IsNullOrEmpty(saleOrder.bodies[i].cmemo))
                {
                    throw new Exception(string.Format("第{0}行子订单号不能为空", (i + 1)));
                }
            }

          
           
                    //取得账套号
                    sql = "SELECT dbo.fn_fd_getAccId()";
                    string cAcc = DbHelper.GetDbString(DbHelper2.GetSingleWithTrans(sql, tran));
                    int iRdid = 0;
                    int iRdsid = 0;

                    //获取主键 id
                    SqlParameter[] param = new SqlParameter[]{
                                         new SqlParameter("@RemoteId","00"),
                                         new SqlParameter("@cAcc_Id",cAcc),
                                         new SqlParameter("@cVouchType","Somain"),
                                         new SqlParameter("@iAmount",saleOrder.bodies.Count),
                                         new SqlParameter("@iFatherId",iRdid),
                                         new SqlParameter("@iChildId",iRdsid)

          };
                    param[4].Direction = ParameterDirection.Output;
                    param[5].Direction = ParameterDirection.Output;
                    DbHelper2.ExecuteSqlWithTrans("sp_getid", param, CommandType.StoredProcedure, tran);
                    iRdid = DbHelper.GetDbInt(param[4].Value);
                    iRdsid = DbHelper.GetDbInt(param[5].Value);
                    iRdsid = iRdsid - saleOrder.bodies.Count;

                    string sql1 = @"insert into so_somain([cSTCode]	
      ,[dDate]	
      ,[cSOCode]	
      ,[cCusCode]	
      ,[cDepCode]	
      ,[cPersonCode]	
      ,[cexch_name]	
      ,[iExchRate]	
      ,[iTaxRate]	
      ,[iStatus]	
      ,[cMaker]	
      ,[bDisFlag]	
      ,[bReturnFlag]	
      ,[cCusName]	
      ,[bOrder]	
      ,[ID]	
      ,[iVTid]	
      ,[cBusType]	
      ,[dPreMoDateBT]	
      ,[dPreDateBT]	
      ,[iverifystate]	
      ,[dcreatesystime]	
      ,[bcashsale],cgatheringplan,iswfcontrolled,cdefine8,ccusperson,cCusOAddress,
cinvoicecompany )
values(@cSTCode	
      ,@dDate	
      ,@cSOCode	
      ,@cCusCode	
      ,@cDepCode	
      ,@cPersonCode	
      ,@cexch_name	
      ,@iExchRate	
      ,@iTaxRate	
      ,@iStatus	
      ,@cMaker	
      ,@bDisFlag	
      ,@bReturnFlag	
      ,@cCusName	
      ,@bOrder	
      ,@ID	
      ,@iVTid	
      ,@cBusType	
      ,@dPreMoDateBT	
      ,@dPreDateBT	
      ,@iverifystate	
      ,getdate()
      ,@bcashsale,@cgatheringplan,1,@cdefine8,@ccusperson,@cCusOAddress,
@cCusCode
)";
                    //20221116  更改为未审核的销售订单，进审批流，提交
                    DbHelper2.ExecuteSqlWithTrans(sql1, new SqlParameter[]{
  new SqlParameter("cSTCode","09"),
 new SqlParameter("dDate",DbHelper.ToDbValue(saleOrder.head.dDate)),
 new SqlParameter("cSOCode",DbHelper.ToDbValue(saleOrder.head.cSOCode)),
 new SqlParameter("cCusCode",DbHelper.ToDbValue(saleOrder.head.cCusCode)),
 new SqlParameter("cDepCode",DbHelper.ToDbValue(saleOrder.head.cDepCode)),
 new SqlParameter("cPersonCode",DbHelper.ToDbValue(saleOrder.head.cPersonCode)),
 new SqlParameter("cexch_name",DbHelper.ToDbValue(saleOrder.head.cExch_name)),
 new SqlParameter("iExchRate",DbHelper.ToDbValue(saleOrder.head.iExchRate)),
 new SqlParameter("iTaxRate",DbHelper.ToDbValue(saleOrder.head.iTaxRate)),
 new SqlParameter("iStatus","1"),
 new SqlParameter("cMaker",DbHelper.ToDbValue(saleOrder.head.cMaker)),
 new SqlParameter("bDisFlag","0"),
 new SqlParameter("bReturnFlag","0"),
 new SqlParameter("cCusName",DbHelper.ToDbValue(saleOrder.head.cCusName)),
 new SqlParameter("bOrder","0"),
 new SqlParameter("ID",iRdid),
 new SqlParameter("iVTid","131555"),
 new SqlParameter("cBusType","分期收款"),
 new SqlParameter("dPreMoDateBT",DbHelper.ToDbValue(saleOrder.bodies[0].dPreDate)),
 new SqlParameter("dPreDateBT",DbHelper.ToDbValue(saleOrder.bodies[0].dPreDate)),
 new SqlParameter("iverifystate","0"),
 new SqlParameter("bcashsale","0"),
  new SqlParameter("cgatheringplan","001"),
  new SqlParameter("cdefine8","否"),
   new SqlParameter("ccusperson",DbHelper.ToDbValue(saleOrder.head.cCusperson)),
    new SqlParameter("cCusOAddress",DbHelper.ToDbValue(saleOrder.head.cCusOAddress)) 


                    }, CommandType.Text, tran);

                    for (int i = 0; i < saleOrder.bodies.Count; i++)
                    {
                        //取税率 
                        decimal iTaxrate = saleOrder.bodies[i].iTaxRate;
                        decimal iSum = saleOrder.bodies[i].iSum;
                        decimal iTax = DbHelper.GetDbdecimal((iSum - iSum / (1 + iTaxrate / 100)).ToString("0.00"));
                        decimal iMoney = iSum - iTax;
                        //无税单价
                        decimal iUnitpricews = iMoney / saleOrder.bodies[i].iQuantity;
                        //string dNatsum = (DbHelper.GetDbdecimal(dr["金额"]) * DbHelper.GetDbdecimal(dr["汇率"])).ToString("0.00");
                        decimal dExchrate = DbHelper.GetDbdecimal(saleOrder.head.iExchRate);

                        iAmount_f += iSum * dExchrate;
                        iAmount += iSum;
                        iRdsid += 1;
                        sql1 = string.Format(@"insert into so_sodetails(
cSOCode,
cInvCode,
dPreDate,
iQuantity,
iNum,
iQuotedPrice,
iUnitPrice,
iTaxUnitPrice,
iMoney,
iTax,
iSum,
iDisCount,
iNatUnitPrice,
iNatMoney,
iNatTax,
iNatSum,
iNatDisCount,
cFree1,
iSOsID,
KL,
KL2,
cInvName,
iTaxRate,
cFree6,
iInvExchRate,
cUnitID,
ID,
dPreMoDate,
iRowNo,cdefine29,cdefine24,bsaleprice,cdefine31,cmemo
)
                                                         values(
@cSOCode,
@cInvCode,
@dPreDate,
@iQuantity,
@iNum,
@iQuotedPrice,
@iUnitPrice,
@iTaxUnitPrice,
@iMoney,
@iTax,
@iSum,
@iDisCount,
@iNatUnitPrice,
@iNatMoney,
@iNatTax,
@iNatSum,
@iNatDisCount,
@cFree1,
@iSOsID,
@KL,
@KL2,
@cInvName,
@iTaxRate,
@cFree6,
@iInvExchRate,
@cUnitID,
@ID,
@dPreMoDate,
@iRowNo,@cdefine29,@cdefine24,@bsaleprice,@cdefine31,@cmemo
)");
                        DbHelper2.ExecuteSqlWithTrans(sql1, new SqlParameter[]{

 new SqlParameter("cSOCode",DbHelper.ToDbValue(saleOrder.head.cSOCode)),
 new SqlParameter("cInvCode",DbHelper.ToDbValue(saleOrder.bodies[i].cInvCode)),
 new SqlParameter("dPreDate",DbHelper.ToDbValue(saleOrder.bodies[i].dPreDate)),
 new SqlParameter("iQuantity",DbHelper.ToDbValue(saleOrder.bodies[i].iQuantity)),
 new SqlParameter("iNum","0"),
 new SqlParameter("iQuotedPrice",DbHelper.ToDbValue(saleOrder.bodies[i].iTaxUnitPrice)),
 new SqlParameter("iUnitPrice",iUnitpricews),
 new SqlParameter("iTaxUnitPrice",DbHelper.ToDbValue(saleOrder.bodies[i].iTaxUnitPrice)),
 new SqlParameter("iMoney",iMoney),
 new SqlParameter("iTax",iTax),
 new SqlParameter("iSum",DbHelper.ToDbValue(saleOrder.bodies[i].iSum)),
 new SqlParameter("iDisCount","0"),
 new SqlParameter("iNatUnitPrice",saleOrder.bodies[i].iTaxUnitPrice*dExchrate),
 new SqlParameter("iNatMoney",iMoney*dExchrate),
 new SqlParameter("iNatTax",iTax*dExchrate),
 new SqlParameter("iNatSum",iSum*dExchrate),
 new SqlParameter("iNatDisCount","0"),
 new SqlParameter("cFree1",""),
 new SqlParameter("iSOsID",iRdsid),
 new SqlParameter("KL","100"),
 new SqlParameter("KL2","100"),
 new SqlParameter("cInvName",""),
 new SqlParameter("iTaxRate",DbHelper.ToDbValue(saleOrder.bodies[i].iTaxRate)),
 new SqlParameter("cFree6",""),
 new SqlParameter("iInvExchRate",DbHelper.ToDbValue(null)),
 new SqlParameter("cUnitID",DbHelper.ToDbValue(null)),
 new SqlParameter("ID",iRdid),
 new SqlParameter("dPreMoDate",DbHelper.ToDbValue(saleOrder.bodies[i].dPreDate)),
 new SqlParameter("iRowNo",i+1),
  new SqlParameter("cdefine29",DbHelper.ToDbValue(saleOrder.bodies[i].cDefine29)),
  new SqlParameter("cdefine31","彭昕雯"),
      new SqlParameter("cdefine24",DbHelper.ToDbValue(saleOrder.bodies[i].cDefine24)),
      new SqlParameter("cmemo",DbHelper.ToDbValue(saleOrder.bodies[i].cmemo)),
        new SqlParameter("bsaleprice",1),
                    }, CommandType.Text, tran);

                        sql = "insert into SO_SODetails_extradefine(isosid,cbdefine6,cbdefine8) values(@isosid,'是','外购')";
                        DbHelper2.ExecuteSqlWithTrans(sql, new SqlParameter[]{
                       new SqlParameter("@isosid",iRdsid) }, CommandType.Text, tran);
                    }




                    tran.Commit();
                }
                catch (Exception exception)
                {
                    tran.Rollback();
                    ret.code = 500;
                    ret.message = exception.Message;
                    return ret;
                }
                if(saleOrder.head.PayStatus=="1")
                {
                    //写入收款单
                    try
                    {

                        AP_CloseBill.Head rdHead = new AP_CloseBill.Head();
                        rdHead.editprop = "A";
                        rdHead.cVouchType = "48";
                        rdHead.dVouchDate = saleOrder.head.dDate;
                        rdHead.cDwCode = saleOrder.head.cCusCode;
                        rdHead.cSSCode = "1";
                        rdHead.iPeriod = DbHelper.GetDbDate(saleOrder.head.dDate).Month.ToString();
                        rdHead.cDeptCode = saleOrder.head.cDepCode;
                        rdHead.cPerson = saleOrder.head.cPersonCode;
                        rdHead.cexch_name = saleOrder.head.cExch_name;
                        rdHead.iExchRate = saleOrder.head.iExchRate;
                        rdHead.iAmount_f = iAmount_f.ToString("0.00");
                        rdHead.iAmount = iAmount.ToString("0.00");
                        rdHead.iRAmount_f = iAmount_f.ToString("0.00");
                        rdHead.iRAmount = iAmount.ToString("0.00");
                        rdHead.cOperator = saleOrder.head.cMaker;
                        rdHead.iSource = "0";
                        rdHead.cSource = "销售";
                        rdHead.cOrderNo = saleOrder.head.cSOCode;
                        rdHead.cFlag = "AR";
                        rdHead.cTypeName = "收款单";
                        rdHead.cPayType = "货款";



                        List<AP_CloseBill.Body> bodies = new List<AP_CloseBill.Body>();
                        //表体也只有1行


                        AP_CloseBill.Body body = new AP_CloseBill.Body();
                        body.cType = "应收款";
                        body.bPrePay = "False";
                        body.iType = "0";
                        body.cCusVen = saleOrder.head.cCusCode;
                        body.iAmt_f = iAmount_f.ToString("0.00");
                        body.iAmt = iAmount.ToString("0.00");
                        body.iRAmt_f = iAmount_f.ToString("0.00");
                        body.iRAmt = iAmount.ToString("0.00");
                        body.cDepCode = saleOrder.head.cDepCode;
                        body.cOrderID = saleOrder.head.cSOCode;
                        body.iOrderType = "0";
                        body.cOrderType = "销售";
                        body.editprop = "A";
                        bodies.Add(body);



                        AP_CloseBill entity = new AP_CloseBill(rdHead, bodies);

                        string cerr, cid, ccode;
                        string xmlconfig = XmlOperation.GetConfigXML().ToString();
                        if (!ApCloseBillDALCO.AddAPCloseBill(entity, xmlconfig, out cerr, out cid, out ccode))
                        {
                            throw new Exception("生成收款单失败：" + cerr);
                        }

                    }
                    catch (Exception ex)
                    {
                        return DBService.ReErrorbool(ex.Message);
                    }
                }
            }
            ret.code = 200;
            ret.message = "导入成功";
            return ret;
        }

            
 





             string GetVoucherCode(DataTable dt1)
            {
                //写单据号，用update
                //DateTime ddt = Convert.ToDateTime(saleOrder.headddate"]);
                //int iyear = (Convert.ToInt32(ddt.Year));
                //int imonth = Convert.ToInt32(ddt.Month);
                //int iday = Convert.ToInt32(ddt.Day);
                //string cDate1 = ddt.ToString("yyyyMMdd");
                ////iyear.ToString() + imonth.ToString().PadLeft(2, '0') + iday.ToString().PadLeft(2, '0');

                ////取最大值，voucherhistory
                string sql = string.Format(@"SELECT cnumber FROM VoucherHistory where cardnumber = 'RR' and  ISNULL(cseed,'') = '' and ISNULL(ccontent,'') = ''
                   ");
                object single = DbHelper2.ExecuteScalar(sql, CanShu.conStr);
                int iMax = 1;
                if (null != single)
                {
                    iMax = Convert.ToInt32(single) + 1;
                    sql = string.Format(@"update VoucherHistory set cnumber ='{0}' where cardnumber = 'RR' and  ISNULL(cseed,'') = '' and ISNULL(ccontent,'') = ''
                    ", iMax);
                    DbHelper2.ExecuteNonQuery(sql,CanShu.conStr);

                }
                else
                {
                    sql = string.Format(@"INSERT INTO VoucherHistory(CardNumber,cContent,cSeed,cNumber,bEmpty)
VALUES('RR',null,null,1,0)");
                    DbHelper2.ExecuteNonQuery(sql, CanShu.conStr);

                }

                return iMax.ToString().PadLeft(10, '0');
            }




  
}
}
